package top.eggcode.common.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.eggcode.common.lang.BeanUnit;
import top.eggcode.common.model.ListPage;
import top.eggcode.common.model.ResponseResult;
import top.eggcode.common.mvc.Responser;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;

/**
 * Title: 数据封装的对象控制器
 * Description: TODO
 * Date: 2021/5/16 8:16
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public abstract class PackBaseController {

    Logger logger = LoggerFactory.getLogger(PackBaseController.class);


    protected <V> ResponseResult<?> pack(V view) {
        return Responser.successful(view);
    }

    protected <T, V> ResponseResult<?> pack(T entity, Class<V> viewType) {
        return Responser.successful(
                BeanUnit.transfer(entity, viewType)
        );
    }

    protected <T, V> ResponseResult<?> pack(List<T> entityList, Function<T, V> build) {
        List<V> viewList = new LinkedList<>();
        entityList.stream()
                .map(build)
                .forEach(viewList::add);
        return Responser.successful(viewList);
    }

    protected <T, V> ResponseResult<?> pack(T entity, Function<T, V> build) {
        return Responser.successful(
                build.apply(entity)
        );
    }

    protected <T, V> ResponseResult<?> pack(List<T> entityList, Class<V> viewType) {
        List<V> viewList = new LinkedList<>();
        entityList.stream()
                .map(entity -> BeanUnit.transfer(entity, viewType))
                .forEach(viewList::add);
        return Responser.successful(viewList);
    }

    protected <T, V> ResponseResult<?> pack(ListPage<T> page, Class<V> viewType) {
        List<T> doList = page.getList();
        List<V> voList = new LinkedList<>();
        doList.stream()
                .map(entity -> BeanUnit.transfer(entity, viewType))
                .forEach(voList::add);
        ListPage<?> view = new ListPage<V>()
                .setNumber(page.getNumber())
                .setSize(page.getSize())
                .setTotal(page.getTotal())
                .setList(voList);
        return Responser.successful(view);
    }

    protected <T, V> ResponseResult<?> pack(ListPage<T> page, Function<T, V> apply) {
        List<T> doList = page.getList();
        List<V> voList = new LinkedList<>();
        doList.stream()
                .map(apply)
                .forEach(voList::add);
        ListPage<?> view = new ListPage<V>()
                .setNumber(page.getNumber())
                .setSize(page.getSize())
                .setTotal(page.getTotal())
                .setList(voList);
        return Responser.successful(view);
    }
}
